import * as echarts from '../../../components/echarts/echarts';

const app = getApp();
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");
const common = require("../../../utils/common");

Page({

  /**f
   * 页面的初始数据
   */
  data: {
    commentRank: 0, // 排名靠前靠后靠中
    examInfo: null,
    studentScore: null,
    scoreAvgList: null,
    examName: null, // 考试名称
    examDate: null, // 考试时间
    examFullScoreArray: null, // 各科满分数组
    subjectArray: null, // 科目数组
    navigatorSubjectArray: null,
    subjectEnglishName: null, // 该科目英文名
    studentName: null, // 考生名字
    examStudentNum: null, // 考试人数
    subjectName: '', // 科目名称
    subjectIndex: 0, // 切换科目索引

    termDateIndex: 0, // termData的索引（左右键选择了哪个学期）
    termDate: '', // 学期日期（用于显示在页面）
    leftTermDateBtnDisabled: false, // 更换时间时，左按钮是否禁用
    rightTermDateBtnDisabled: false, // 更换时间时，右按钮是否禁用
    ecIsShow: true, // 控制ec图是否显示
    ecBarIsHidden: false, // 控制ecBar是否显示
    ec: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const lineChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(lineChart);
        lineChart.setOption(getLineChartOption(data));
        return lineChart;
      }
    },
    scoreLineCharts: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const scoreChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(scoreChart);
        scoreChart.setOption(getScoreChartOption(data));
        return scoreChart;
      }
    },
    flag: 1,
    // 学期列表数据
    termData: [],
    // 成绩数据（按学期查询出来的）
    termScoreData: {},

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let params = {
      studentId: options.studentId,
      schoolId: options.schoolId,
      gradeType: options.gradeType,
      grade: options.grade,
      examId: options.examId,
    }
    let subjectName = options.subjectName;
    this.getStudentExamScore(params, subjectName);
    // 要按学期查看变化
    //TODO 暂时不放出来，按学期选择成绩的数据有问题
    // this.getStudentTermExamScoreList(params)

    this.setData({
      userType: app.globalData.userType,
      rightTermDateBtnDisabled: true,
    })
  },

  /**
   * 查询学生成绩
   */
  async getStudentExamScore(params, subjectName) {
    let result = await requestUtil.request('POST', api.getStudentExamScore, params);
    let examInfo = result.data.data.examInfo;
    let studentScore = result.data.data.studentScore[0];
    if (studentScore == null || !result.data.data.studentScore.length > 0) {
      wx.showModal({
        title: '警告',
        content: '未找到该场考试的相关成绩，请等待教师上传成绩后再次打开。'
      })
      return;
    }
    let examName = examInfo.examName; // 考试名称
    let examDate = examInfo.regClosingTime; // 考试时间
    let examStudentNum = studentScore.examStudentNum; // 考试人数
    let studentName = studentScore.studentName; // 学生名字
    let subjectArray = examInfo.examSubject.split(','); // 科目数组
    let examFullScoreArray = examInfo.examFullScore.split(','); // 考试成绩数组
    let subjectEnglishNameMap = app.globalData.subjectEnglishNameMap(); // 科目英文名
    let scoreAvgList = {};
    let subjectEnglishName = '';
    let commentRank = 0; // 评价，0排名靠前，1排名靠后, 2排名中间
    let zws = Math.round(studentScore.examStudentNum / 2); // 中位数
    for (let i of studentScore.scoreAvgList) {
      for (let j in subjectArray) {
        if (subjectName == subjectArray[j] && subjectArray[j] == i.subjectName) {
          let str = subjectEnglishNameMap.get(subjectArray[j]) + 'Score';
          let rank = subjectEnglishNameMap.get(subjectArray[j]) + 'Rank';
          subjectEnglishName = subjectEnglishNameMap.get(subjectArray[j]);
          i.myScore = studentScore[str];
          i.myRank = studentScore[rank];
          scoreAvgList = i;
        }
      }
    }
    // 班级排名前中后
    if (scoreAvgList.myRank < (zws - 3)) {
      commentRank = 0;
    } else if (scoreAvgList.myRank > (zws + 3)) {
      commentRank = 1;
    } else if ((zws - 3) < scoreAvgList.myRank && scoreAvgList.myRank < (zws + 3)) {
      commentRank = 2;
    }
    let commentScore = '';
    if (scoreAvgList.myScore > scoreAvgList.avgScore) {
      commentScore = '高于'
    } else if (scoreAvgList.myScore == scoreAvgList.avgScore) {
      commentScore = '等于'
    } else if (scoreAvgList.myScore < scoreAvgList.avgScore) {
      commentScore = '低于'
    }
    // 跳转用的科目数组
    let navigatorSubjectArray = subjectArray.slice(0);
    navigatorSubjectArray.unshift('总分');
    let subjectIndex = 0;
    for (let si = 0; si < navigatorSubjectArray.length; si++) {
      if (subjectName === navigatorSubjectArray[si]) {
        subjectIndex = si;
      }
    }
    this.setData({
      examInfo,
      studentScore,
      examName,
      examDate,
      examFullScoreArray,
      navigatorSubjectArray,
      subjectArray,
      studentName,
      examStudentNum,
      subjectIndex,
      scoreAvgList,
      subjectEnglishName,
      subjectName,
      commentRank,
      commentScore,
      params,
    })

    // 进入页面时获取当前学期所有成绩
    this.getCurrTermScoreList(params, studentScore.termId);
  },

  /**
   * 查询学期列表
   */
  async getStudentTermExamScoreList(params) {
    let termRes = await requestUtil.request('GET', api.getTermList, null);
    let termList = termRes.data.data; // 学期列表
    let termData = [];
    for (let i of termList) {
      let obj = {
        termId: i.id,
        termName: i.termName,
        startDate: i.startDate,
        endDate: i.endDate,
        termDate: (i.startDate + '-' + i.endDate).toString()
      }
      termData.push(obj);
    }
    this.setData({
      termData: termData,
      termDateIndex: termData.length - 1,
      leftTermDateBtnDisabled: termData.length - 1 == 0 ? true : false
    })
  },

  /**
   * 获取当前学期所有考试成绩
   */
  async getCurrTermScoreList(params, id) {
    let param = {
      termId: id,
      schoolId: params.schoolId,
      studentId: params.studentId,
      grade: params.grade
    }
    let currScoreRes = await requestUtil.request('POST', api.getStudentTermExamScore, param);
    let scoreList = currScoreRes.data.data;
    let subjectName = this.data.subjectName; // 科目名
    let subjectRank = this.data.subjectEnglishName + 'Rank';
    let subjectScore = this.data.subjectEnglishName + 'Score';
    let termScoreListData = {
      termName: scoreList[0].termName,
      termId: scoreList[0].termId,
    };
    let scoreDataList = [];
    // 数据量大的时候可能会卡？
    for (let i of scoreList) {
      for (let j of i.scoreAvgList) {
        if (subjectName == j.subjectName) {
          let obj = {
            rank: i[subjectRank],
            score: i[subjectScore],
            avgScore: j.avgScore,
            gradeAvgScore: j.gradeAvgScore,
            highestScore: j.highestScore,
            lowestScore: j.lowestScore,
            //TODO 注意，日后可能要改这里，因为教师万一输错顺序，整个比较列表都会错误
            id: i.examId,
            createTime: i.createTime
          }
          scoreDataList.push(obj);
        }
      }
    }
    termScoreListData.data = scoreDataList;
    this.setData({
      termScoreData: termScoreListData,
      termDate: scoreList[0].termName
    })
  },

  /**
   * 回到首页（其实就是上一页）
   */
  backTotalPage: function () {
    wx.navigateBack({
      delta: 1,
    })
  },

  /**
   * 切换科目
   */
  subjectChange: function (e) {
    let subject = this.data.navigatorSubjectArray[e.detail.value];
    let params = this.data.params;
    if (subject == this.data.subjectName) {
      return;
    }
    if (subject == '总分') {
      wx.navigateBack({
        delta: 1,
      })
    } else {
      wx.redirectTo({
        url: './score?studentId=' + params.studentId +
          '&schoolId=' + params.schoolId +
          '&gradeType=' + params.gradeType +
          '&grade=' + params.grade +
          '&examId=' + params.examId +
          '&subjectName=' + subject
      })
    }
  },

  /**
   * 学期成绩排名变化时间改变
   * //TODO 暂时不用，接口有问题，考试数据跟后台的不一样
   */
  changeTermDate: function (e) {
    let done = e.currentTarget.dataset.done;
    let index = this.data.termDateIndex;
    let length = this.data.termData.length - 1;
    switch (done) {
      case 'left':
        if (index == 0) {
          break;
        } else if (index > 0) {
          --index;
          this.setData({
            termDate: this.data.termData[index].termName,
            termDateIndex: index,
            rightTermDateBtnDisabled: false,
            leftTermDateBtnDisabled: index == 0 ? true : false
          });
          // 传日期获取排名变化然后给echarts渲染
          this.getCurrTermScoreList(this.data.params, this.data.termData[index].termId);
        }
        break;
      case 'right':
        if (index == length) {
          break;
        } else if (index < length) {
          ++index;
          this.setData({
            termDate: this.data.termData[index].termName,
            termDateIndex: index,
            leftTermDateBtnDisabled: false,
            rightTermDateBtnDisabled: index == length ? true : false
          });
          // 传日期获取排名变化然后给echarts渲染
          this.getCurrTermScoreList(this.data.params, this.data.termData[index].termId);
        }
        break;
    }
  },

})

function getLineChartOption(d) {
  let dateList = []; // termScoreData.data 中的 id 集合，用id做横坐标 
  let valueList = []; // termScoreData.data中的 rank 的集合，排名做纵坐标
  let data = d.termScoreData.data;
  for (let i = 0; i < data.length; i++) {
    dateList.push(data[i].id);
    valueList.push(data[i].rank);
  }

  return {
    grid: {
      containLabel: true,
      top: '10%',
      bottom: '15%'
    },
    tooltip: {
      // trigger: 'none'
      trigger: 'axis' // 显示提示框
    },
    xAxis: {
      boundaryGap: true,
      inverse: true,
      data: dateList,
      axisLabel: {
        show: false,
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      // x: 'center',
      type: 'value',
      // data: ['0%', '20%', '40%', '60%', '80%', '100%'],
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '排名',
      type: 'line',
      smooth: true,
      data: valueList,
    }]
  };
}

function getScoreChartOption(d) {
  let dateList = d.termScoreData.data.map(o => o.id);
  let scoreList = d.termScoreData.data.map(o => o.score);
  let avgScoreList = d.termScoreData.data.map(o => o.avgScore);
  let gradeAvgScoreList = d.termScoreData.data.map(o => o.gradeAvgScore);
  let highestScoreList = d.termScoreData.data.map(o => o.highestScore);
  let lowestScoreList = d.termScoreData.data.map(o => o.lowestScore);

  return {
    grid: {
      containLabel: true,
      top: '25%',
      bottom: '15%'
    },
    legend: {
      data: ['我的', '班平均分', '级平均分', '最高分', '最低分']
    },
    tooltip: {
      // trigger: 'none'
      trigger: 'axis' // 显示提示框
    },
    xAxis: {
      boundaryGap: true,
      inverse: true,
      data: dateList,
      axisLabel: {
        show: false,
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '我的',
      type: 'line',
      smooth: true,
      data: scoreList,
    }, {
      name: '班平均分',
      type: 'line',
      smooth: true,
      data: avgScoreList,
    }, {
      name: '级平均分',
      type: 'line',
      smooth: true,
      data: gradeAvgScoreList,
    }, {
      name: '最高分',
      type: 'line',
      smooth: true,
      data: highestScoreList,
    }, {
      name: '最低分',
      type: 'line',
      smooth: true,
      data: lowestScoreList,
    }, ]
  };
}